package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 组合数字二
 * 在数组中查找目标  使一个数组加起来的和等于target
 */
public class Solution29 {
    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> ans = new ArrayList<>();
    boolean[] used;
    int sum = 0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        used = new boolean[candidates.length];
        Arrays.fill(used,false);

        Arrays.sort(candidates);
        backtracking(candidates,target,0);
        return ans;
    }


    public void backtracking(int[] candidates, int target,int startIndex){
        if(sum == target){
            ans.add(new ArrayList(path));
        }
        //遍历数组
        for(int i = startIndex ; i < candidates.length ;i++){
            //如果大于直接返回
            if(candidates[i] + sum > target){
                break ;
            }
            //执行去重的逻辑
            if(i > 0 && candidates[i] == candidates[i - 1] && !used[i - 1]){
                continue;
            }
            used[i] = true;
            sum += candidates[i];
            path.add(candidates[i]);
            // 每个节点仅能选择一次，所以从下一位开始
            backtracking(candidates, target, i + 1);
            used[i] = false;
            sum -= candidates[i];
            path.removeLast();

        }
    }
}
